package com.wuzhun.wxmp.common;

/**
 *
 * 错误拦截
 * @author renbaolin
 * @date  2021/3/5.
 */
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(ServiceException.class)
    public Object handleException(ServiceException e) {
        LOGGER.error("GlobalExceptionHandler.handleException ServiceException:", e);
        return jsonObject(e.getMessage(), e.errorCode);
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e) {
        LOGGER.error("GlobalExceptionHandler.handleException Exception:", e);
        return jsonObject(e.getMessage(), ResultCode.SERVICE_EXCEPTION.getErrorCode());
    }

    private JSONObject jsonObject(String msg, String errorCode) {
        if (msg == null || msg.equals("") || msg.length() > 50) {
            msg = ResultCode.SERVICE_EXCEPTION.getErrorMessage();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", errorCode);
        jsonObject.put("error", msg);
        return jsonObject;
    }
}
